import { build, defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import chalk from 'chalk'
import { resolve } from 'path'
import glob from 'fast-glob'
import ts from '@rollup/plugin-typescript'

import buildCss from './buildCss.js'

const args = process.argv.slice(2)[0]
const step = (text, color) => console.log(chalk[color](text))

const run = async () => {
  if (!args) {
    step('未获取到打包目录', 'red')
    return
  }
  step('打包目录: ' + args, 'red')
  const files = await glob(`packages/${args}/**/*.ts`, { onlyFiles: true })
  const entries = files.reduce((acc, file) => {
    const name = file.replace('packages/', '').replace('/index.ts', '')
    acc[name] = resolve('/', file)
    return acc
  }, {})

  /* 总样式文件出口 */
  const stylePath = args.split('/')[0]

  /* 打包组件配置 */
  const viteCompPackDeploy = {
    plugins: [
      react(),
      ts({
        target: 'ESNext',
        rootDir: `packages/${args}/`,
        declaration: true,
        declarationDir: `dist/${args}`,
        exclude: 'node_modules/**',
        allowSyntheticDefaultImports: true
      })
    ],
    build: {
      emptyOutDir: false,
      lib: {
        entry: entries,
        name: 'charts',
        fileName: format => `index.${format === 'cjs' ? 'js' : 'mjs'}`,
        /* es和common */
        formats: ['es', 'cjs']
      },
      outDir: 'dist',
      cssCodeSplit: false,
      rollupOptions: {
        external: ['react', 'react-dom', 'antd'],
        output: {
          assetFileNames: `${stylePath}/[name]/jui[extname]`,
          entryFileNames: '[name]/index.[format].js',
          globals: {
            react: 'react',
            antd: 'antd',
            'react-dom': 'react-dom'
          }
        }
      }
    }
  }
  /* 打包组件 */
  step('开始打包组件', 'magenta')
  await build(defineConfig(viteCompPackDeploy))
  step('组件打包完成', 'cyan')
  /* 样式分离并可按需加载*/
  step('开始分离组件样式', 'magenta')
  await buildCss(args)
  step('分离组件样式完成', 'cyan')
}

run()
